package swu.cx.learning_10_17

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

class BottomBar:LinearLayout {
    var index = -1
    var selectCallback:((Int)->Unit)? = null
     var bgPic:Int = 0
     var selectIcon:Int = 0
     var selectColor:Int = 0
     var normalColor:Int = 0
     var Bottomtext:String? = null
        set(value) {
            field = value
            iconTextView?.text = value
        }
    var mSelected:Boolean = false
        set(value) {
            field = value
            changUI()
        }
    private var iconImageView:ImageView? = null
    private var iconTextView:TextView ? =null
    private fun changUI() {
        if(mSelected){
            iconImageView?.setImageResource(selectIcon)
            iconTextView?.setTextColor(selectColor)
        }else{
            iconImageView?.setImageResource(bgPic)
            iconTextView?.setTextColor(normalColor)
        }
    }

    constructor(context: Context):super(context){
        init()
    }
    constructor(context: Context,attrs: AttributeSet):super(context,attrs){
        parseAttr(attrs)
        init()

    }
    private fun parseAttr(attrs: AttributeSet){
        val typedArray:TypedArray = context.obtainStyledAttributes(attrs,R.styleable.BottomBar)
        bgPic = typedArray.getResourceId(R.styleable.BottomBar_normalIcon,R.drawable.circle)
        selectIcon = typedArray.getResourceId(R.styleable.BottomBar_selectIcon,R.drawable.circle_selected)
        selectColor  = typedArray.getColor(R.styleable.BottomBar_selectColor,Color.RED)
        Bottomtext = typedArray.getString(R.styleable.BottomBar_text)
        normalColor = typedArray.getColor(R.styleable.BottomBar_normalColor,Color.BLACK)
        mSelected = typedArray.getBoolean(R.styleable.BottomBar_selected,false)
        typedArray.recycle()
    }
    private fun init(){
        orientation = VERTICAL
        gravity = Gravity.CENTER
        iconImageView =  ImageView(context).apply {
             val lp = LinearLayout.LayoutParams(dpTopx(32),dpTopx(32))
            addView(this,lp)
        }
        iconTextView = TextView(context).apply {
            val lp = LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT
            )
            lp.gravity = Gravity.CENTER_HORIZONTAL
            addView(this,lp)
        }
    }
    private fun dpTopx(dp:Int)=(context.resources.displayMetrics.density*dp).toInt()
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if(event?.action==MotionEvent.ACTION_DOWN) {
            if(!mSelected){
                mSelected = true
                selectCallback?.let {
                    it(index)
                }
            }
        }
        return true
    }
}